package com.sykj.huxianlong.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sykj.bean.sys.SysUser;
import com.sykj.huxianlong.entity.*;
import com.sykj.huxianlong.mapper.WithdrawalMapper;
import com.sykj.huxianlong.service.IFlowInfoService;
import com.sykj.huxianlong.service.ILogService;
import com.sykj.huxianlong.service.IUserService;
import com.sykj.huxianlong.service.IWithdrawalService;
import com.sykj.huxianlong.utli.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zzy
 * @version 1.0
 * @date 2020/8/4 9:33
 */
@Service
@Slf4j
public class WithdrawalServiceImpl implements IWithdrawalService {

    @Autowired
    private WithdrawalMapper withdrawalMapper;
    @Autowired
    private IFlowInfoService flowInfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ILogService logService;



    @Override
    @Transactional
    public void insertWithdrawal(Withdrawal Withdrawal) {
        //记录日志
        ProcessLog bean = new ProcessLog();
        String username = userService.getCurrentUser("user").getUserName();
        String userid = userService.getCurrentUser("user").getUserId();
        String puserid = userService.getCurrentUser("user").getParentUserId();
        if(null != Withdrawal.getExid()) {//更新
            withdrawalMapper.updateById(Withdrawal);
            bean.setOrderNo(Withdrawal.getExid());
            bean.setOperValue(username+"修改审批单");
//         bean.setOperValue(currentUser.getUserName() + "修改审批单");
        }else {
            long orderNo = CommonUtil.genId();
            bean.setOrderNo(orderNo);
            Withdrawal.setExid(orderNo);
            Withdrawal.setExstate(0);

            //  vacationOrder.setUserId(currentUser.getUserId());//当前登录用户id
            Withdrawal.setUserid(userid);
            Withdrawal.setExcode("1001");
          //  Withdrawal.setBusltype("2001");
            Withdrawal.setExtype(4001);

            withdrawalMapper.insert(Withdrawal);
            //  bean.setOperValue(currentUser.getUserName() + "填写审批单");
            bean.setOperValue(username + "填写审批单");
        }

        logService.insertLog(bean);

    }

    /**
     * 填写提现审批单
     * @param
     * @return
     */
    @Override
    public List<WithdrawalVo> queryWithdrawal() {
        String username = userService.getCurrentUser("user").getUserName();
        String userid = userService.getCurrentUser("user").getUserId();
        String puserid = userService.getCurrentUser("user").getParentUserId();
        List<WithdrawalVo> WithdrawalPage = withdrawalMapper.queryWithdrawalVo(userid);//当前登录用户id
        return WithdrawalPage;
    }

    @Override
    public Withdrawal queryWithdrawal(Long exid) {
        QueryWrapper<Withdrawal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exid",exid);
        return  withdrawalMapper.selectOne(queryWrapper);

    }

    @Override
    @Transactional
    public void updateState(Long exid, Integer state) {
        Withdrawal Withdrawal = new Withdrawal();
        Withdrawal.setExstate(state);
        Withdrawal.setExid(exid);
        withdrawalMapper.updateById(Withdrawal);

    }

    @Override
    public boolean submitApply(Long exid) {
        boolean res = true;
        //匹配流程并指定申请人
        Map<String, Object> variables = new HashMap<>();
        String username = userService.getCurrentUser("user").getUserName();
        String userid = userService.getCurrentUser("user").getUserId();
        String puserid = userService.getCurrentUser("user").getParentUserId();
        // User currentUser = userService.getCurrentUser();//获取当前登录的用户
        String flowId = "";
        //匹配流程之前查询是否已经匹配过
        FlowMain flowMain = flowInfoService.queryFlowMainByOrderNo(exid);
        if(ObjectUtil.isNull(flowMain)) { //返回true 如果提供的引用null则返回false。
            // variables.put("applyuser",currentUser.getUserId());
            variables.put("applyuser",userid);//点前登录用户的id
            flowId = flowInfoService.resolves(exid,variables);
        }else {
            //flowid =流程ID(启动流程时生成的编码)
            flowId = String.valueOf(flowMain.getFlowId());
        }
        if(StrUtil.isBlank(flowId)) {
            /**
             * StrUtil.isBlank
             * 字符串是否为空白 空白的定义如下：
             * 1、为null
             * 2、为不可见字符（如空格）
             * 3、""
             */
            res = false;
            return res;
        }
        //流程流转，对应工作流提交成功
        Task task = flowInfoService.queryTaskByInstId(flowId);
        if(ObjectUtil.isNull(task)) {
            res = false;
            return res;
        }
        variables.put("subState","success");
        log.info("------------->当前办理任务ID:{}",task.getId());
        taskService.complete(task.getId(),variables);
        //更新审批单状态
        this.updateState(exid, SysConstant.REVIEW_STATE);

        //记录日志
        ProcessLog bean = new ProcessLog();


        User user = userService.queryUserById(puserid);//获取当前登录用户的上级领导id
        bean.setOrderNo(exid);
        bean.setTaskId(task.getId());
        bean.setTaskName(task.getName());
        bean.setTaskKey(task.getTaskDefinitionKey());
        bean.setApprovStatu("submitApply");
        bean.setOperValue(username + "提交申请,待【"+user.getUserName()+"】审核");

        //bean.setOperValue(currentUser.getUserName() + "提交申请,待【"+user.getUserName()+"】审核");
        logService.insertLog(bean);
        return res;
    }

    @Override
    @Transactional
    public void delWithdrawal(Long exid) {
        this.updateState(exid, SysConstant.OBSOLETE_STATE);
        //记录日志
        // User currentUser = userService.getCurrentUser();
        String username = userService.getCurrentUser("user").getUserName();
        String userid = userService.getCurrentUser("user").getUserId();
        String puserid = userService.getCurrentUser("user").getParentUserId();
        ProcessLog bean = new ProcessLog();
        //User user = userService.queryUserById(currentUser.getParentUserId());
      //  SysUser user = userService.queryUserById("103");
        bean.setOrderNo(exid);
        bean.setApprovStatu("DELETE");
        //bean.setOperValue(currentUser.getUserName() + "删除审批单");
        bean.setOperValue(username + "删除审批单");

        logService.insertLog(bean);
    }
}
